package com.building.util;/**
 * Created by LH on 2021/3/5.
 */

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.JWTVerifier;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName JwtUtil
 * @Description: TODO
 * @Author LH
 * @Date 2021/3/5
 **/
public class JwtUtil {
    public static final String SECRET = "FH_SSO_1234567890";//token密钥   对称的那个密钥

    public static final int MAX_AGE = 10;//有效期十天

    /**
     * JWT生成Token.<br/>
     *
     * JWT构成: header, payload, signature
     *
     */
    public static String createToken(Integer userId,String userPhone) throws Exception {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.DATE, MAX_AGE);

        String token = JWT.create() // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP").withClaim("userId", null == userId ? null : userId.toString())
                .withClaim("aud", "APP").withClaim("userPhone", userPhone)
                .withIssuedAt(new Date()) // sign time
                .withExpiresAt(nowTime.getTime()) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature


        return token;
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            // token 校验失败, 抛出Token验证非法异常
            return null;
        }
        return jwt.getClaims();
    }

    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */
    public static Map<String,Object> getUser(String token) {
        Map<String, Claim> claims = verifyToken(token);
        if(claims == null) {
            return null;
        }
        Claim userId = claims.get("userId");
        Claim userPhone = claims.get("userPhone");

        if (null == userId || StringUtils.isEmpty(userId.asString())) {
            // token 校验失败, 抛出Token验证非法异常
            return null;
        }
        if (null == userPhone || StringUtils.isEmpty(userPhone.asString())) {
            // token 校验失败, 抛出Token验证非法异常
            return null;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId.asString());
        map.put("userPhone",userPhone.asString());

        return map;
    }

    public static void main(String[] args) {
        Map<String, Object> user = JwtUtil.getUser("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJBUFAiLCJwaG9uZSI6IjEyMyIsImlzcyI6IlNlcnZpY2UiLCJleHAiOjE2MTYzMTg4NjgsImlhdCI6MTYxNTQ1NDg2OCwibWVtYmVySWQiOiI1In0.1GaYEbpkdJBT-fvw0EjGTi8zpXvsTPo51XoKh2tfWUk");
        System.out.println(user.get("userId"));
        System.out.println(user.get("userPhone"));
    }
}
